<template>

    <div class="full-width full-height page-content">
      <!-- 搜索区 -->
      <collapse ref="collapse">
        <template v-slot:content>
          <div
            class="flex form-inline justify-between no-wrap padding-r-20 padding-l-20"
            style="margin-top: 6px; padding-bottom: 0"
          >
            <div class="left box flex">
              <div class="flex items-center">
                <customized-switch
                  class="margin-b-20"
                  style="width: 128px; height: 24px"
                  :options="dateTypeOption"
                  v-model="dateType"
                  @change="changeDateType()"
                />
              </div>
              <div class="margin-l-20" v-show="dateType === 'date'">
                <span>日期：</span>
                <date-picker
                  format="YYYY-MM-DD"
                  class="margin-b-20"
                  :editable="false"
                  :clearable="false"
                  type="date"
                  v-model="dateRange"
                  range
                  placeholder="选择日期范围"
                  style="width: 240px"
                />
              </div>
              <div class="margin-l-20" v-show="dateType === 'time'">
                <span>时间：</span>
                <date-picker
                  format="MM-DD HH:00 "
                  class="margin-b-20"
                  :editable="false"
                  :clearable="false"
                  v-model="timeRange"
                  type="datetime"
                  range
                  placeholder="选择时间范围"
                  style="width: 240px"
                ></date-picker>
              </div>
            </div>
            <div class="flex no-wrap">
              <q-btn
                class="btn margin-r-10"
                outline
                dense
                emit-value
                map-options
                options-dense
                color="primary"
                @click="resetSearch()"
                label="重置"
              />
              <q-btn
                class="btn"
                unelevated
                type="submit"
                color="primary"
                label="查询"
                @click="searchData()"
              />
            </div>
          </div>
          <div class="form-inline" style="padding-bottom: 0px">
            <div class="left box flex">
              <div class="flex items-center">
                <customized-switch
                  class="margin-b-20"
                  style="width: 228px; height: 24px"
                  :options="treeOptions"
                  v-model="treeType"
                />
              </div>
              <div class="margin-l-20" v-show="treeType === '1'">
                <workshop-search v-model="queryParams" ref="workShopSearch" :is-shift="false" @endDevice="endDevice"/>
              </div>
              <div class="margin-l-20" v-show="treeType === '2'">
                <workshop-input v-model="queryParams" ref="workShopInput"/>
              </div>
            </div>
          </div>
          <div
            class="form-inline bottom padding-r-20 padding-l-20"
            style="padding-bottom: 14px"
          >
            <q-btn
              class="btn margin-r-10"
              outline
              color="primary"
              :disable="disableDownloadExcel"
              @click="exportExcelNew"
              >导出Excel</q-btn
            >
            <q-toggle
              v-model="showScale"
              label="启用缩放"
              left-label
              @input="changeScale"
              style="position: absolute; right: 20px"
            />
          </div>
        </template>
      </collapse>
      <div
        style="flex: 1; margin-top: 6px"
        class="overflow-auto scrollbar padding-r-20 padding-l-20"
      >
        <div class="relative-position">
          <div class="absolute">共计{{ deciveCount }}台设备</div>
          <div class="full-width text-center">生产总件数：{{ total }}</div>
        </div>
        <div
          ref="circulateStat"
          class="margin-b-20 margin-t-20"
          style="width: 100%; height: 390px"
        ></div>
        <q-table
          :data="tableData"
          :columns="tableColumns"
          row-key="number"
          id="table"
          class="myTable scroll stick-first-col"
          style="margin: 0 0 15px"
          :pagination.sync="pagination"
          :hide-bottom="!!tableData.length"
          color="primary"
          :loading="tableLoading"
        >
          <template v-slot:header="props">
            <q-tr>
              <q-th v-for="(item, index) in props.cols" :key="index">
                {{item.label}}
              </q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr class="tr">
              <q-td>
                {{  props.row[0].name }}
              </q-td>
              <q-td class="link-td align-center" v-for="(item, index) in props.row.slice(1, props.row.length)" :key="index" @click="showCountDetail(item)">
                {{ item.count }}
              </q-td>
            </q-tr>
          </template>
        </q-table>
      </div>
      <CountDetailDialog  ref="countDetail" :table-data="countDetailData" :table-loading="countDetailLoading"/>
    </div>
</template>

<script>
import Collapse from 'src/components/collapse'
import CustomizedSwitch from 'src/components/customized-switch'
import circulateStat from '../../boot/statistics/circulate-stat'
import { toTime } from 'src/filters/filter'
import echarts from 'echarts'
import { mapGetters } from 'vuex'
import moment from 'moment'
import CountDetailDialog from './components/count-detail-dialog'
// import XLSX from 'xlsx'
import _ from 'lodash'
import { addListener } from 'resize-detector'
export default {
  name: 'circulate-stat',
  components: {
    Collapse,
    CustomizedSwitch,
    CountDetailDialog
  },
  computed: {
    ...mapGetters([
      'userInfo',
      'client'
    ]),
    disableDownloadExcel () {
      return this.total === 0
    },
    deciveCount () {
      if (this.cloneTreeType === '2') {
        return this.deviceIds.length
      }
      return this.cloneParams.devices[0] === 'all' ? this.deviceOptions.length : this.deviceIds.length
    }
  },
  data () {
    return {
      treeOptions: [
        {
          value: '1',
          label: '按组织架构'
        },
        {
          value: '2',
          label: '按调度线'
        }
      ],
      treeType: '1',
      cloneTreeType: '1',
      queryParams: {
        location: {
          id: null,
          level: null,
          label: '',
          hash: ''
        },
        devices: ['all'],
        workshop: '',
        dispatchLine: '',
        workshopId: ''
      },
      cloneParams: {
        devices: ['all']
      },
      exportParams: {},
      deviceOptions: [], // 所选设备Id列表
      showScale: false, // 是否可以缩放
      requestId: null, // 导出唯一标识
      timeRange: [null, null],
      dateRange: [moment(new Date()).subtract(7, 'days').toDate(), new Date()],
      dateType: 'date',
      circulateStat: null, // 稼动率图表
      dateTypeOption: [
        {
          value: 'time',
          label: ' 时间 '
        },
        {
          value: 'date',
          label: ' 日期 '
        }
      ],
      pagination: {
        rowsPerPage: 0
      },
      deviceIds: [], // 所选设备Id列表
      tableColumns: [
      ], // 表格头部数据
      tableData: [],
      total: 0, // 总件数
      tableLoading: false,
      countDetailLoading: false,
      countDetailData: []
    }
  },
  mounted () {
    addListener(this.$refs.circulateStat, this.$utils.debounce(() => {
      if (this.circulateStat) {
        this.circulateStat.resize()
      }
    }, 100))
    this.getListInit()
  },
  methods: {
    endDevice (val) {
      this.deviceOptions = val
    },
    getListInit () {
      this.$refs.workShopSearch.getWorkshops().then(() => {
        this.getData()
      })
    },
    // 查找所有的同一路径的父节点名称
    getParentNames (array, label) {
      // 名字是机床名称和机床列表拼接的，去掉机床编号在进行查询 例如：模拟盒子(mm)
      label = label.replace(/\((.+?)\)/g, '')
      let stack = []
      let going = true
      // 递归查找父元素名称
      let walker = (array, label) => {
        array.forEach(item => {
          if (!going) return
          stack.push(item['label'])
          if (item['label'] === label) {
            going = false
          } else if (item['children']) {
            walker(item['children'], label)
          } else {
            stack.pop()
          }
        })
        if (going) stack.pop()
      }
      walker(array, label)
      // 过滤父节点为default的节点
      stack = stack.filter(item => {
        if (item !== 'default') {
          return item
        }
      })
      // 删除最后一个目标本身
      stack = stack.slice(0, stack.length - 1)
      return stack.join('/')
    },

    // 图表缩放
    changeScale () {
      let option = _.cloneDeep(this.circulateStat.getOption())
      option.dataZoom[0].disabled = !this.showScale
      this.circulateStat.clear()
      this.circulateStat.setOption(option)
    },
    // 获取数据
    getData () {
      let params = {
        dispatchingLineId: this.treeType === '2' ? this.queryParams.dispatchLine : null,
        queryType: this.treeType
      }
      const { location } = this.queryParams
      if (this.treeType === '2') {
        this.deviceIds = _.get(this.$refs.workShopInput.dispatchLineOptions.find(v => v.value === this.queryParams.dispatchLine), 'devices', [])
      } else {
        this.deviceIds = this.queryParams.devices[0] === 'all' ? [] : this.queryParams.devices
        params.deviceTreeReqVO = {
          deviceIds: this.queryParams.devices[0] !== 'all' ? this.queryParams.devices : [],
          level: location.level || null,
          schemeId: location.id || null
        }
      }
      if (this.deviceIds.length || this.queryParams.workshopId) {
        if (this.dateType === 'date') {
          params['type'] = 2
          params['startTime'] = moment(this.dateRange[0]).format('YYYY-MM-DD') + 'T00:00:00'
          params['endTime'] = moment(this.dateRange[1]).format('YYYY-MM-DD') + 'T00:00:00'
        } else {
          params['type'] = 1
          params['startTime'] = moment(this.timeRange[0]).startOf('hour').format('YYYY-MM-DDTHH:mm:ss')
          params['endTime'] = moment(this.timeRange[1]).startOf('hour').format('YYYY-MM-DDTHH:mm:ss')
        }
        this.cloneTreeType = _.cloneDeep(this.treeType)
        this.getCirculateStatTableData(params)
        this.getCirculateStatChartData(params)
      } else {
        this.$message.warning('所选设备数量为0，请重新选择')
      }
    },
    // 获取表格数据
    getCirculateStatTableData (params) {
      if (this.dateType === 'date') {
        this.getTableDayColumns(this.dateRange)
      } else {
        this.getTableTimeColumns(this.timeRange)
      }
      this.tableLoading = true
      this.tableData = []
      this.cloneParams = _.cloneDeep(this.queryParams)
      this.exportParams = _.cloneDeep(params)
      circulateStat.getDeviceProductCount(params).then(res => {
        this.tableData = []
        const data = res.data
        if (this.dateType === 'date') {
          this.calcTypeDay(data)
        } else {
          this.calcTypeTime(data)
        }
      }).finally(() => {
        this.tableLoading = false
      })
    },
    calcTypeDay (data) {
      if (data && data.length > 0) {
        // 计算日历选中的全部日期
        const startDate = moment(this.dateRange[0])
        const endDate = moment(this.dateRange[1])
        let diff = endDate.diff(startDate, 'days')
        // 日期数组
        const dateArr = []
        // 统计单日内总数数组
        const totalArr = []
        for (let i = 0; i <= diff; i++) {
          const firstDate = moment(this.dateRange[0])
          const dateDay = firstDate.add(i, 'd').format('YYYY-MM-DD')
          dateArr.push(dateDay)
          totalArr.push({ count: 0 })
        }
        const result = []
        const lastDeviceId = this.deviceIds[this.deviceIds.length - 1]
        // 遍历数据
        data.forEach(item => {
          const list = item.list
          const obj = {}
          // 把返回有数据的放在对象中
          list.forEach(l => {
            const time = moment(l.time).format('YYYY-MM-DD')
            obj[time] = l.count
          })
          // 每一天的数据，如果没有的话就显示--
          // 并根据日期累加综合
          const arr = dateArr.map((date, index) => {
            // 如果当前日期下存在数据
            if (obj[date]) {
              // 如果是按调度线
              if (this.treeType === '2') {
                // 取最后一个设备
                if (item.deviceId === lastDeviceId) {
                  totalArr[index].count = obj[date]
                }
              } else {
                totalArr[index].count += obj[date]
              }
            }
            return {
              deviceId: item.deviceId,
              date,
              count: obj[date] || '--'
            }
          })
          // 添加第一项数据名称
          arr.unshift({ 'name': item.productName })
          result.push(arr)
        })
        // 添加合计名称
        if (this.treeType === '2') {
          totalArr.unshift({ 'name': '有效生产数' })
        } else {
          totalArr.unshift({ 'name': '合计' })
        }
        result.push(totalArr)
        this.tableData = result
      }
    },
    calcTypeTime (data) {
      if (!data || data.length === 0) return
      const startDate = moment(this.timeRange[0]).startOf('hour')
      const endDate = moment(this.timeRange[1]).startOf('hour')
      let diff = endDate.diff(startDate, 'hours')
      // 日期数组
      const dateArr = []
      // 统计单日内总数数组
      const totalArr = []
      totalArr.push({ count: 0 })
      dateArr.push(startDate.format('MM-DD HH:mm'))
      for (let i = 0; i <= diff - 1; i++) {
        const dateDay = startDate.add(1, 'h').format('MM-DD HH:mm')
        dateArr.push(dateDay)
        totalArr.push({ count: 0 })
      }
      const lastDeviceId = this.deviceIds[this.deviceIds.length - 1]
      const result = []
      // 遍历数据
      data.forEach(item => {
        const list = item.list
        const obj = {}
        // 把返回有数据的放在对象中
        list.forEach(l => {
          obj[moment(l.time).format('MM-DD HH:mm')] = { count: l.count, date: l.time }
        })
        // 每一天的数据，如果没有的话就显示--
        // 并根据日期累加综合
        const arr = dateArr.map((date, index) => {
          // 如果当前日期下存在数据
          if (obj[date]) {
            // 如果是按调度线
            if (this.treeType === '2') {
              // 取最后一个设备
              if (item.deviceId === lastDeviceId) {
                totalArr[index].count = obj[date].count
              }
            } else {
              totalArr[index].count += obj[date].count
            }
          }
          return {
            deviceId: item.deviceId,
            date: obj[date] ? obj[date].date : '',
            count: obj[date] ? obj[date].count : '--'
          }
        })
        // 添加第一项数据名称
        arr.unshift({ 'name': item.productName })
        result.push(arr)
      })
      // 添加合计名称
      if (this.treeType === '2') {
        totalArr.unshift({ 'name': '有效生产数' })
      } else {
        totalArr.unshift({ 'name': '合计' })
      }
      result.push(totalArr)
      this.tableData = result
    },
    // 获取图表数据
    getCirculateStatChartData (params) {
      circulateStat.getDeviceProductCountTime(params).then(res => {
        let xAxisList = []
        let dataList = []
        if (res.data.length) {
          res.data.forEach(item => {
            xAxisList.push(this.dateType === 'date' ? moment(item.data).format('MM-DD') : moment(item.time).format('MM-DD HH:mm'))
            dataList.push(item.count)
          })
        }
        this.total = _.sumBy(res.data, 'count')
        this.getCirculateStatChart(xAxisList, dataList)
      })
    },
    // 获取生产计数统计图表
    getCirculateStatChart (xAxisList, dataList) {
      this.circulateStat = echarts.init(this.$refs.circulateStat)
      // const xAxisList = ['05-01', '05-02', '05-03', '05-04', '05-05', '05-06']
      // const dataList = [200, 357, 604, 832, 748, 1079]
      const option = {
        grid: {
          top: 35,
          bottom: 35,
          left: 60,
          right: 0
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
            label: {
              show: false
            }
          },
          formatter: (params, ticket, callback) => {
            let htmlStr = ''
            let value = params[0].value
            let color = `linear-gradient(#44D8C6, #5F77FD)`
            let name = params[0].name

            htmlStr += '<div>' + name + '</div>'
            htmlStr += '<div>'
            htmlStr += '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-image:' + color + ';"></span>'
            htmlStr += '实际生产件数：' + value

            htmlStr += '</div>'
            return htmlStr
          }
        },
        legend: {
          data: [{ icon: 'pin', name: '实际生产件数' }, '实际生产趋势'],
          right: 0,
          textStyle: {
            padding: [3, 0, 0, 0]
          }
        },
        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: 0,
            disabled: true
          }
        ],
        xAxis: {
          type: 'category',
          data: xAxisList,
          axisTick: {
            show: true, // 隐藏X轴刻度
            alignWithLabel: false
          },
          axisLabel: {
            show: true,
            margin: 20,
            textStyle: {
              color: '#333333', // X轴文字颜色
              fontSize: 14
            }
          },
          axisLine: {
            show: true, // 隐藏X轴轴线
            lineStyle: {
              color: '#d3d3d3'
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '件数',
          nameTextStyle: {
            color: '#333333',
            align: 'right',
            fontSize: 14
          },
          nameGap: 20,
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#DDD'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            textStyle: {
              color: '#333333',
              fontSize: 14
            }
          },
          axisLine: {
            show: false
          }
        },
        series: [{
          type: 'bar',
          name: '实际生产件数',
          barWidth: 16,
          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: '#44D8C6'
              },
              {
                offset: 1,
                color: '#5F77FD'
              }]),
              barBorderRadius: [6, 6, 0, 0]
            }
          },
          label: {
            show: false
          },
          data: dataList
        }, {
          type: 'line',
          name: '实际生产趋势',
          lineStyle: {
            normal: {
              width: 5,
              color: '#5F77FD'
            }
          },
          symbolSize: 10,
          itemStyle: {
            normal: {
              color: '#5F77FD',
              borderWidth: 3,
              borderColor: '#5F77FD'
            },
            emphasis: {
              color: '#5F77FD',
              borderColor: '#5F77FD'
            }
          },
          smooth: 0.4,
          data: dataList
        }]
      }

      // 基于准备好的dom，初始化echarts实例
      if (this.circulateStat) {
        this.circulateStat.clear()
        this.circulateStat.setOption(option)
      } else {
        this.$nextTick(() => {
          this.circulateStat = echarts.init(this.$refs.circulateStat)
          this.circulateStat.setOption(option)
        })
      }
    },
    // 重置
    resetSearch () {
      this.dateType = 'date'
      this.treeType = '1'
      this.dateRange = [moment(new Date()).subtract(7, 'days').toDate(), new Date()]
      this.timeRange = [moment(new Date()).subtract(6, 'hours').toDate(), moment(new Date()).toDate()]
      Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
      this.$refs.workShopSearch.initData()
      this.$refs.workShopInput.initData()
    },
    changeDateType () {
      if (!this.timeRange[0] && !this.timeRange[1] && this.dateType === 'time') {
        this.timeRange = [moment(new Date()).subtract(6, 'hours').toDate(), moment(new Date()).toDate()]
      }
    },
    onSubscribe () {
      if (this.client) {
        this.client.subscribe(
          `${this.CommonConfig.socketConfig.SOCKET_TOPIC.uploadFile.subscribeTopic}${this.requestId}`, this.onMessageArrived, { id: `${this.requestId}` }
        )
      } else {
        setTimeout(() => {
          this.onSubscribe()
        }, 200)
      }
    },
    closeUbscribeTopic () {
      this.client.unsubscribe(`${this.requestId}`)
      this.$q.loading.hide()
    },
    async onMessageArrived (message) {
      let msg = JSON.parse(message.body).data
      if (msg.requestId !== this.requestId) {
        return
      }
      if (msg.code + '' !== '200') {
        this.$showErrTips('导出异常，请稍后重试')
        this.closeUbscribeTopic()
        return
      }
      let excelName = ''
      console.log(this.exportParams)
      if (this.dateType === 'date') {
        excelName = `${moment(this.exportParams.startTime).format('YYYYMMDD')}-${moment(this.exportParams.endTime).format('YYYYMMDD')}_机台报表_生产计数统计`
      } else {
        excelName = `${moment(this.exportParams.startTime).startOf('hour').format('MMDDHHmm')}-${moment(this.exportParams.endTime).startOf('hour').format('MMDDHHmm')}_机台报表_生产计数统计`
      }

      await this.$saveFileForBlob(msg.data, `${excelName}.xls`)
      this.closeUbscribeTopic()
      this.$message.success('数据请求成功,请保存文件')
    },
    exportExcelNew () {
      let exportParams = this.exportParams
      // if (this.dateType === 'date') {
      //   exportParams.startTime = moment(this.dateRange[0]).format('YYYY-MM-DD') + 'T00:00:00'
      //   exportParams.endTime = moment(this.dateRange[1]).format('YYYY-MM-DD') + 'T00:00:00'
      //   exportParams.type = 2
      // } else {
      //   exportParams.startTime = moment(this.timeRange[0]).startOf('hour').format('YYYY-MM-DDTHH:mm:ss')
      //   exportParams.endTime = moment(this.timeRange[1]).startOf('hour').format('YYYY-MM-DDTHH:mm:ss')
      //   exportParams.type = 1
      // }
      this.$q.loading.show()
      const params = [{ name: '' }]
      const res = this.$getUploadPath(params, '')
      this.requestId = res.fileNameNew
      exportParams['requestId'] = res.fileNameNew
      exportParams.queryType = this.cloneTreeType
      this.onSubscribe()
      if (this.cloneTreeType === '2') {
        // exportParams.dispatchingLineId = this.treeType === '2' ? this.queryParams.dispatchLine : null
        circulateStat.exportProductCountReportsByDispatch(exportParams).then(res => {
          if (res.code !== '1200') {
            this.$showErrTips('导出异常，请稍后重试')
            this.closeUbscribeTopic()
          }
        }).catch(res => {
          this.closeUbscribeTopic()
        })
      } else {
        // const { location } = this.queryParams
        // exportParams.deviceTreeReqVO = {
        //   deviceIds: this.queryParams.devices[0] !== 'all' ? this.queryParams.devices : [],
        //   level: location.level || null,
        //   schemeId: location.id || null
        // }
        circulateStat.exportProductCountReports(exportParams).then(res => {
          if (res.code !== '1200') {
            this.$showErrTips('导出异常，请稍后重试')
            this.closeUbscribeTopic()
          }
        }).catch(res => {
          this.closeUbscribeTopic()
        })
      }
    },
    // 去除数组中的空值
    trimSpace (array) {
      for (var i = 0; i < array.length; i++) {
        if (array[i] === ' ' || array[i] == null || typeof (array[i]) === 'undefined') {
          array.splice(i, 1)
          i = i - 1
        }
      }
      return array
    },
    // 转化成和时间格式一样的数据
    formatReasultTimeData (arr) {
      const result = [arr[0]]
      for (let i = 0; i < result.length; i++) {
        for (let y = 0; y < arr.length; y++) {
          if (result[i].deviceId === arr[y].deviceId) {
            result[i].resultTimeAndCount = this.duplicate([...result[i].resultTimeAndCount, ...arr[y].resultTimeAndCount])
          } else {
            result.push(arr[y])
          }
        }
      }
      return result
    },
    //  去除重复数据
    duplicate (arr) {
      var result = []
      var obj = {}
      for (var i = 0; i < arr.length; i++) {
        if (!obj[arr[i].time]) {
          result.push(arr[i])
          obj[arr[i].time] = true
        }
      }
      return result
    },
    // 格式化导出excel需要的数据
    formatReasultData (arr) {
      var result = {}
      arr.forEach(v1 => {
        result[v1.deviceId] = {
          arr: v1.resultTimeAndCount,
          name: v1.deviceName
        }
      })
      const resu = []
      for (let i in result) {
        result[i].arr.forEach((item, index, Arr) => {
          const total = Arr.reduce((pre, cur) => {
            return pre + cur.count
          }, 0)
          const a = []
          a[0] = result[i]['name']
          // 判断是日期类型取 data 字段，时间类型取time字段
          if (this.dateType === 'date') {
            a[1] = item.data
          } else {
            a[1] = toTime(item.time)
          }
          a[2] = item.count
          resu.push(a)
          if (index === Arr.length - 1) {
            resu.push([result[i]['name'], '小计', total])
          }
        })
      }
      return resu
    },
    // 查询
    searchData () {
      if (this.dateType === 'date' && Math.abs(moment(this.dateRange[0]).diff(moment(this.dateRange[1]), 'days')) > 60) {
        this.$message.warning('日期范围不可超过60天')
      } else if (this.dateType === 'time' && Math.abs(moment(this.timeRange[0]).diff(moment(this.timeRange[1]), 'hours')) > 24) {
        this.$message.warning('时间范围不可超过24小时')
      } else {
        this.showScale = false
        this.getData()
      }
    },
    /**
       * 判断所选时间范围是否超出
       * @returns {boolean} 是否超出
       */
    dateIsOver () {
      let isOver = false
      isOver = (this.dateType === 'date' && Math.abs(moment(this.dateRange[0]).diff(moment(this.dateRange[1]), 'days')) > 60)
      if (this.dateType === 'date') {
        isOver = Math.abs(moment(this.dateRange[0]).diff(moment(this.dateRange[1]), 'days')) > 60
      } else {
        isOver = Math.abs(moment(this.timeRange[0]).diff(moment(this.timeRange[1]), 'hours')) > 7 * 24
      }
      return isOver
    },

    /**
     * 显示详情弹框
     */
    showCountDetail (row) {
      if (isNaN(Number(row.count)) || !row.deviceId) return
      const workshopId = this.treeType === '2' ? this.queryParams.workshop : this.queryParams.workshopId
      this.countDetailLoading = true
      this.countDetailData = []
      const params = {
        time: moment(row.date).format('YYYY-MM-DDTHH:mm:ss'),
        id: row.deviceId,
        type: this.dateType === 'date' ? 2 : 1,
        workshopId: workshopId
      }
      circulateStat.getDeviceProductCountList(params).then(res => {
        this.countDetailData = res.data
      }).finally(() => {
        this.countDetailLoading = false
      })
      this.$refs.countDetail.showDialog()
    },
    /**
     * 获取表头
     */
    getTableDayColumns (val) {
      const startDate = moment(val[0])
      const endDate = moment(val[1])
      const member = [{ label: '加工设备', align: 'left', field: 'productName', name: 'productName' }]
      let diff = endDate.diff(startDate, 'days')
      for (let i = 0; i <= diff; i++) {
        const firstDate = moment(val[0])
        const dateDay = firstDate.add(i, 'd').format('YYYY-MM-DD')
        member.push({
          label: `${dateDay}(${firstDate.format('dddd')})`,
          name: dateDay,
          field: dateDay,
          align: 'center'
        })
      }
      this.tableColumns = member
    },
    getTableTimeColumns (val) {
      const startDate = moment(val[0]).startOf('hours')
      const endDate = moment(val[1]).startOf('hours')
      const startDateValue = startDate.format('MM-DD HH:mm')
      const member = []
      let diff = endDate.diff(startDate, 'hours')
      for (let i = 0; i <= diff - 1; i++) {
        const dateDay = startDate.add(1, 'h').format('MM-DD HH:mm')
        member.push({
          label: `${dateDay}`,
          name: dateDay,
          field: dateDay,
          align: 'left'
        })
      }
      member.unshift({
        label: startDateValue,
        name: startDateValue,
        field: startDateValue,
        align: 'left'
      })
      member.unshift({ label: '加工设备', align: 'left', field: 'productName', name: 'productName' })
      this.tableColumns = member
    }
  }
}
</script>

<style lang="stylus" scoped>
.link-td{
  cursor: pointer;
  color $primary
}
.align-center{
  text-align: center;
}
.tr:nth-last-child(1){
  td{
    background-color #f3f3f3
    border-top 1px solid #d3d3d3
    color #333
    cursor auto
  }
}
</style>
